package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

type Student struct {
	Id     int    `db:"id"`
	Name   string `db:"name"`
	Sex    string `db:"sex"`
	Age    string `db:"age"`
	Course string `db:"course"`
}

var Db *sqlx.DB

func init() {
	database, err := sqlx.Open("mysql", "root:@tcp(127.0.0.1:3306)/test")
	if err != nil {
		fmt.Println("mysql open failed,", err)
		return
	}
	Db = database
}

func main() {
	conn, err := Db.Begin()
	if err != nil {
		fmt.Println("begin failed :", err)
		return
	}
	r, err := Db.Exec("insert into student(name, sex, age, course)values(?, ?, ?, ?)", "王五", "男", 18, "Golang")
	if err != nil {
		fmt.Println("exec failed, ", err)
		err = conn.Rollback()
		return
	}
	id, err := r.LastInsertId()
	if err != nil {
		fmt.Println("exec failed,", err)
		err = conn.Rollback()
		return
	}
	fmt.Println("insert succ:", id)

	r, err = Db.Exec("insert into student(name, sex, age, course)values(?,?,?,?)", "赵六", "男", 18, "Linux、Python、Java")
	if err != nil {
		fmt.Println("exec failed, ", err)
		err = conn.Rollback()
		return
	}
	id, err = r.LastInsertId()
	if err != nil {
		fmt.Println("exec failed, ", err)
		err = conn.Rollback()
		return
	}
	fmt.Println("insert succ:", id)
	err = conn.Commit()
}
